﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading;
using System.Threading.Tasks;

namespace CenterControllerServer.WebApi.Extensions
{
    public static class RedisServiceExtensions
    {
        private static string RedisShellMutexName = Guid.NewGuid().ToString();
        private static Mutex RedisShellMutex = new Mutex(false, RedisShellMutexName);

        public static void AddRedisService(this IServiceCollection services)
        {
            var assembly = Assembly.GetExecutingAssembly().Location;
            var fileInfo = new FileInfo(assembly);
            var currentDirectory = fileInfo.Directory.FullName;
            var redisServerExeFile = Path.Combine(currentDirectory, @"Tools\Redis-x64-5.0.14.1\redis-server.exe");
            var redisClientExeFile = Path.Combine(currentDirectory, @"Tools\Redis-x64-5.0.14.1\redis-cli.exe");
            var configFile = Path.Combine(new FileInfo(redisServerExeFile).Directory.FullName, "redis.windows.conf");
            var redisShellExeFile = Path.Combine(currentDirectory, @"Tools\RedisShell\RedisShell.exe");
            var info = new ProcessStartInfo();
            var args = RedisShellMutexName + " " + $"\"{redisServerExeFile}\"" + " " + $"\"{configFile}\"" + " " + $"\"{redisClientExeFile}\"";
            info.FileName = redisShellExeFile;
            info.Arguments = args;
            info.UseShellExecute = false;

            // 锁定互斥锁。
            RedisShellMutex.WaitOne(Timeout.Infinite);
            var shellProcess = Process.Start(info);

            if (shellProcess.HasExited)
            {
                throw new InvalidOperationException("启动Redis服务失败！");
            }

            //Configure other services up here.
            var multiplexer = ConnectionMultiplexer.Connect("localhost");
            services.AddSingleton<IConnectionMultiplexer>(multiplexer);
        }
    }
}
